<template>
  <div>
    <a-modal
      :title="title"
      wrapClassName="modal"
      :bodyStyle="{padding:'30px 50px'}"
      width="90%"
      v-model="visible"
      :confirmLoading="confirmLoading"
      @ok="handleSubmit"
    >
      <div class="elem-layer-right" style="top:70px;">
        <a-button v-if="okText!==''" key="submit" type="primary" :loading="confirmLoading" @click="handleSubmit">
          {{ okText }}
        </a-button>
      </div>

      <apply-form
        ref="applyform"
        style="clear:both"
        :from="from"
        :data="applyData"
        :key="applyData.outRecordId"
        :disabledList="disabledList"
        :status="pageStatus"
        :showSubmit="false" />
      <template slot="footer">
        <a-button key="back" @click="cancel">
          关闭
        </a-button>
        <!-- <a-button v-if="okText!==''" key="submit" type="primary" :loading="confirmLoading" @click="handleSubmit">
          {{ okText }}
        </a-button> -->
      </template>
    </a-modal>
    <rollout-check-modal ref="checkModal" @ok="checkModalSubmit"/>
  </div>
</template>
<script>
import ApplyForm from './ApplyForm'
import RolloutCheckModal from '../modules/RolloutCheckModal.vue'
import { refInUpdate, refInSave } from '@/api/referral'
// import pick from 'lodash.pick'
export default {
  name: 'ApplyModal',
  props: {
    from: {
      type: String,
      default: ''
    }
  },
  components: {
    ApplyForm,
    RolloutCheckModal
  },
  data () {
    return {
      description: '',
      visible: false,
      confirmLoading: false,
      disabledList: [],
      pageStatus: 'edit',
      applyData: {},
      title: '操作信息',
      okText: ''
    }
  },
  beforeCreate () {
  },
  created () {
  },
  methods: {
    reports (record, title) {
      var poptitle = title || ''
      this.init(record, poptitle, 'edit')
      this.okText = '确认报到'
      // 注意，转入转出必须同时传name和code
      this.disabledList = ['patientName', 'patientIdcard', 'patientGender', 'patientAge', 'patientMedicareType', 'patientDob', 'patientMedicareNumber',
        'patientPhone', 'patientAddress', 'outHospitalName', 'outHospitalCode', 'outDeptCode', 'outDeptName', 'outDoctorCode', 'outDoctorName', 'outReason',
        'patientCertificateType', 'patientType', 'outTime', 'primaryDiagnosis', 'hospitalTurn', 'zyh', 'inHospitalName', 'inHospitalCode']
    },
    edit (record, title) {
      var poptitle = title || ''
      this.init(record, poptitle, 'edit')
      this.okText = '保存'
      this.disabledList = ['name']
    },
    view (record, title) {
      var poptitle = title || ''
      this.init(record, poptitle, 'details')
      this.okText = ''
      this.$nextTick(() => {
        // this.form.setFieldsValue(pick(this.mdl, 'dictId', 'dictName', 'dictType', 'status', 'remark')) // 挑选键值对
      })
    },
    check (record, title) {
      var poptitle = title || ''
      this.init(record, poptitle, 'details')
      this.okText = '审核'
    },
    init (record, title, status) {
      this.pageStatus = status
      if (title) {
        this.title = title
      }
      this.applyData = record
      this.visible = true
    },
    cancel () {
      this.visible = false
    },
    validate (call) {
      const {
        $refs: { applyform }
      } = this
      const ApplyForm = new Promise((resolve, reject) => {
        if (this.pageStatus !== 'details') {
          applyform.form.validateFields((err, values) => {
            if (err) {
              reject(err)
              return
            }
            resolve(values)
          })
        } else {
          const getdata = applyform.form.getFieldsValue()
          if (getdata && getdata.length > 0) {
            resolve(getdata)
          } else {
            reject(new Error('未获取到数据！'))
          }
        }
      })
      Promise.all([ApplyForm])
        .then(values => {
          const res = values[0]
          const params = Object.assign({}, this.applyData, res, {
            // outTime: (typeof res.outTime === 'object' && res.outTime.format()) || '',
            inPlanTime: (res.inPlanTime && typeof res.inPlanTime === 'object' && res.inPlanTime.format('YYYY-MM-DD HH:mm:ss')) || ''
          })
          console.log('表单取值', params)
          call && call(params)
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    checkModalSubmit () {
      this.visible = false
      this.$emit('ok')
    },
    baodaoConfirm (params) {
      const that = this
      that.$confirm({
        title: '报到提示',
        content: '确认患者报到信息无误',
        onOk () {
          return new Promise((resolve, reject) => {
            refInSave(params).then(res => {
              if (res.code === 200) {
                that.$message.success('报到更新成功！')
                that.$emit('ok')
                that.visible = false
                resolve()
              } else {
                that.$message.error(res.message)
              }
            }).catch((err) => {
              that.$message.error(err.message)
            }).finally(() => {
            })
          }).catch(() => console.log('确认出错!'))
        },
        onCancel () {}
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      const that = this
      if (this.okText === '确认报到') {
        that.validate(params => {
          that.baodaoConfirm(params)
          // that.confirmLoading = true
          // refInUpdate(params).then(res => {
          //   that.confirmLoading = false
          //   if (res.code === 200) {
          //     that.baodaoConfirm({ outRecordId: params.outRecordId })
          //   } else {
          //     that.$message.error(res.message)
          //   }
          // }).catch(() => {
          //   that.confirmLoading = false
          // }).finally(() => {
          //   that.confirmLoading = false
          // })
        })
      }
      if (this.okText === '审核') {
        this.$refs.checkModal.edit(this.applyData)
      }

      // this.form.validateFields((err, values) => {
      //   if (!err) {
      //     console.log('Received values of form: ', values)
      //     this.confirmLoading = true
      //     saveDictType(values).then(res => {
      //       if (res.code === 200) {
      //         this.$message.success('保存成功')
      //         this.$emit('ok')
      //         this.visible = false
      //       } else {
      //         this.$message.success(res.message)
      //       }
      //     }).catch(() => {
      //     }).finally(() => {
      //       this.confirmLoading = false
      //     })
      //   }
      // })
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
<style>
.modal .ant-modal {
  top: 64px !important;
}
</style>
